package com.avocado.base.validator.resources;

import com.avocado.base.repository.ResourcesRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

@Slf4j
public class ResourcesAddCodeValidator implements ConstraintValidator<ResourcesAddCodeValidation, String> {


    private final ResourcesRepository resourcesRepository;

    public ResourcesAddCodeValidator(ResourcesRepository resourcesRepository) {

        this.resourcesRepository = resourcesRepository;
    }


    @Override
    public void initialize(ResourcesAddCodeValidation constraintAnnotation) {

    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {

        try {
            //可以为空，但不能已经存在的
            if(StringUtils.isEmpty(value)||StringUtils.isBlank(value)){
                return Boolean.TRUE;
            }

            long count=resourcesRepository.getCountByCode(value);

            return count<1L;

        } catch (Exception ex) {
            log.error(ex.getLocalizedMessage());
        }
        return false;
    }
}
